import { Badge, List } from 'antd-mobile';
import React, { Component } from 'react';
import { connect } from 'react-redux'

@connect(
  state => state
)
class Msg extends Component {
  getLast(arr) {
    return arr[arr.length - 1]
  }
  render() {
    const Item = List.Item
    const Brief = Item.Brief
    const userid = this.props.user._id
    const userinfo = this.props.chat.users
    const msgGroup = {}
    // 根据聊天信息分组
    this.props.chat.chatmsg.forEach(v => {
      msgGroup[v.chatid] = msgGroup[v.chatid] || []
      msgGroup[v.chatid].push(v)
    })
    // 根据消息发送的最后时间来进行排序
    const chatList = Object.values(msgGroup).sort((a, b) => {
      const a_last = this.getLast(a).create_time
      const b_last = this.getLast(b).create_time
      return b_last - a_last
    })
    return (
      <div>
        <List>
          {chatList.map(v => {
            // 获取最新的信息
            const lastItem = this.getLast(v)
            if (!v[0].from) {
              return null
            }
            const targetId = v[0].from === userid ? v[0].to : v[0].from
            const unreadNum = v.filter(v => !v.read && v.to === userid).length
            const name = userinfo[targetId] ? userinfo[targetId].name : ''
            const avatar = userinfo[targetId] ? userinfo[targetId].avatar : ''
            return (
              <List key={lastItem._id}>
                <Item
                  extra={<Badge text={unreadNum}></Badge>}
                  thumb={require(`../img/${avatar}.png`).default}
                  arrow="horizontal"
                  onClick={() => {
                    this.props.history.push(`/chat/${targetId}`)
                  }}
                >
                  {lastItem.content}
                  <Brief>{name}</Brief>
                </Item>
              </List>
            )
          })}
        </List>
      </div>
    )
  }
}

export default Msg
